package com.jt.service;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.xml.crypto.Data;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Service
public class FileServiceImpl implements  FileService {

    @Value("${file.localDir}")
    private   String localDir;

    @Value("${file.url}")
    private  String  urlPath;

    @Override
    public ImageVO upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String  regex="^.+\\.(jpg|png)$";
        boolean matches = originalFilename.matches(regex);
        if(!matches){
           return null;
        }

        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            int width = read.getWidth();
            int height = read.getHeight();
            if (width==0||height==0)
                return  null;
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }

        //文件相对的目录的生成
        String virtualPath = new SimpleDateFormat("/YYYY/MM/dd/").format(new Date());

        //文件名的生成
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件后缀
        String fileName = uuid+originalFilename.substring(originalFilename.lastIndexOf("."));



        //绝对路径是否存在
        File  file1=new File(localDir+virtualPath);
        System.out.println("图片的绝对路径"+localDir+virtualPath);

        if(!file1.exists()){
            file1.mkdirs();
        }

        try {
            file.transferTo(new File(localDir+virtualPath+fileName));
            //封装VO对象
            ImageVO  imageVO=new ImageVO();
            imageVO.setUrlPath(urlPath+virtualPath+fileName);
            imageVO.setFileName(fileName);
            imageVO.setVirtualPath(localDir+virtualPath+fileName);

            return  imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }
    }

    @Override
    public void deleteFile(String virtualPath) {
//        File file=new File(localDir+virtualPath);
        File file=new File(virtualPath);
        file.delete();
    }

}
